package com.allm.ai.common.service;

import com.allm.ai.common.entity.AiModelTag;
import com.allm.ai.common.entity.ModelTag;
import com.allm.ai.common.repository.AiModelTagRepository;
import com.allm.ai.common.repository.ModelTagRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * AI模型标签关联服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AiModelTagService {

    private final AiModelTagRepository aiModelTagRepository;
    private final ModelTagRepository modelTagRepository;

    /**
     * 为模型添加标签
     */
    @Transactional
    public void addTagsToModel(Long modelId, List<Long> tagIds) {
        // 验证标签是否存在且启用
        List<ModelTag> tags = modelTagRepository.findAllById(tagIds);
        List<ModelTag> activeTags = tags.stream()
                .filter(tag -> tag.getIsActive() != null && tag.getIsActive())
                .collect(Collectors.toList());
        
        if (activeTags.size() != tagIds.size()) {
            throw new IllegalArgumentException("部分标签不存在或已禁用");
        }

        // 批量创建或激活关联
        for (Long tagId : tagIds) {
            // 检查是否已存在关联
            if (aiModelTagRepository.existsByModelIdAndTagId(modelId, tagId)) {
                // 如果存在但被禁用，则重新激活
                AiModelTag existingTag = aiModelTagRepository.findByModelIdAndTagId(modelId, tagId)
                        .stream().findFirst().orElse(null);
                if (existingTag != null && !existingTag.getIsActive()) {
                    existingTag.setIsActive(true);
                    aiModelTagRepository.save(existingTag);
                    log.info("重新激活模型标签关联: modelId={}, tagId={}", modelId, tagId);
                }
            } else {
                // 创建新关联
                AiModelTag modelTag = new AiModelTag();
                modelTag.setModelId(modelId);
                modelTag.setTagId(tagId);
                modelTag.setIsActive(true);
                aiModelTagRepository.save(modelTag);
                log.info("创建新的模型标签关联: modelId={}, tagId={}", modelId, tagId);
            }
        }
    }

    /**
     * 软删除模型的标签关联
     */
    @Transactional
    public void removeTagsFromModel(Long modelId, List<Long> tagIds) {
        aiModelTagRepository.softDeleteByModelIdAndTagIdIn(modelId, tagIds);
        log.info("软删除模型标签关联: modelId={}, tagIds={}", modelId, tagIds);
    }

    /**
     * 硬删除模型的标签关联
     */
    @Transactional
    public void hardRemoveTagsFromModel(Long modelId, List<Long> tagIds) {
        aiModelTagRepository.deleteByModelIdAndTagIdIn(modelId, tagIds);
        log.info("硬删除模型标签关联: modelId={}, tagIds={}", modelId, tagIds);
    }

    /**
     * 设置模型的标签（替换所有现有标签）
     */
    @Transactional
    public void setModelTags(Long modelId, List<Long> tagIds) {
        // 先软删除所有现有标签关联
        aiModelTagRepository.softDeleteByModelId(modelId);
        
        // 添加新标签
        if (tagIds != null && !tagIds.isEmpty()) {
            addTagsToModel(modelId, tagIds);
        }
        log.info("设置模型标签: modelId={}, tagIds={}", modelId, tagIds);
    }

    /**
     * 获取模型的启用标签
     */
    public List<ModelTag> getModelTags(Long modelId) {
        return modelTagRepository.findByModelId(modelId);
    }

    /**
     * 获取模型的所有标签（包括禁用的关联）
     */
    public List<ModelTag> getModelTagsIncludeInactive(Long modelId) {
        return modelTagRepository.findByModelIdIncludeInactive(modelId);
    }

    /**
     * 根据标签获取启用的模型ID列表
     */
    public List<Long> getActiveModelIdsByTagId(Long tagId) {
        return aiModelTagRepository.findActiveModelIdsByTagId(tagId);
    }

    /**
     * 根据标签获取模型ID列表（包括禁用的关联）
     */
    public List<Long> getModelIdsByTagId(Long tagId) {
        return aiModelTagRepository.findByTagId(tagId)
                .stream()
                .map(AiModelTag::getModelId)
                .collect(Collectors.toList());
    }

    /**
     * 激活模型的标签关联
     */
    @Transactional
    public void activateModelTags(Long modelId, List<Long> tagIds) {
        List<AiModelTag> existingTags = aiModelTagRepository.findByModelId(modelId)
                .stream()
                .filter(tag -> tagIds.contains(tag.getTagId()))
                .collect(Collectors.toList());

        for (AiModelTag tag : existingTags) {
            if (!tag.getIsActive()) {
                tag.setIsActive(true);
                aiModelTagRepository.save(tag);
            }
        }
        log.info("激活模型标签关联: modelId={}, tagIds={}", modelId, tagIds);
    }

    /**
     * 禁用模型的标签关联
     */
    @Transactional
    public void deactivateModelTags(Long modelId, List<Long> tagIds) {
        aiModelTagRepository.softDeleteByModelIdAndTagIdIn(modelId, tagIds);
        log.info("禁用模型标签关联: modelId={}, tagIds={}", modelId, tagIds);
    }

    /**
     * 检查模型和标签的关联是否启用
     */
    public boolean isModelTagActive(Long modelId, Long tagId) {
        return aiModelTagRepository.existsByModelIdAndTagIdAndIsActiveTrue(modelId, tagId);
    }
}